package com.ruitu.mall_98_2.mine;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.beanu.arad.Arad;
import com.beanu.arad.base.my_base.Config;
import com.beanu.arad.base.my_base.MyBaseActivity;
import com.beanu.arad.support.glide.transformations.GlideImageLoader;
import com.beanu.arad.widget.progressactivity.ProgressLayout;
import com.bumptech.glide.Glide;
import com.hjq.permissions.Permission;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.view.CropImageView;
import com.ruitu.mall_98_2.R;
import com.ruitu.mall_98_2.mvp.contract.AccountSettingContract;
import com.ruitu.mall_98_2.mvp.model.AccountSettingModel;
import com.ruitu.mall_98_2.mvp.presenter.AccountSettingPresenter;
import com.ruitu.router_module.AppHolder;
import com.ruitu.router_module.CommonUtils;
import com.ruitu.router_module.bean.User;
import com.ruitu.router_module.utils.PermissionUtil;

import java.io.File;
import java.util.ArrayList;

import okhttp3.MultipartBody;

public class AccountSettingActivity extends MyBaseActivity<AccountSettingPresenter, AccountSettingModel> implements AccountSettingContract.View {
    //    private TextView tv_log_out;//退出登录
    private TextView tv_nickname;//昵称
    private TextView tv_sex;//性别
    private ImageView iv_head;
    private RelativeLayout ll_header;
    private RelativeLayout rl_nickname;//昵称
    private RelativeLayout rl_sex;//性别
    private RelativeLayout rl_address_manager;//地址管理
    private RelativeLayout rl_account_and_security;//账号与安全
    private RelativeLayout rl_setting;//设置

    //选择图片的集合
    private ArrayList<ImageItem> imageItems = new ArrayList<>();

    private AlertDialog alertDialog;//
    private PopupWindow popupWindow;
    private String userNick;
    private String sexStatus = null;
    private String sex;

    @Override
    protected int getLayoutRes() {
        return R.layout.activity_account_setting;
    }

    @Override
    protected ProgressLayout findProgressLayout() {
        return null;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (null != savedInstanceState){//可以认为不正常
            finish();
        }
    }

    private void initData() {
        if (CommonUtils.isLoginToActivity(this)) {
            User user = AppHolder.instance().getUser();
            if (TextUtils.equals(user.getSex(), "1")) {
                tv_sex.setText("男");
            } else if (TextUtils.equals(user.getSex(), "0")) {
                tv_sex.setText("女");
            } else {
                tv_sex.setText("请选择");
            }
            tv_nickname.setText(user.getNickName());
            Glide.with(this).load(Config.BASE_URL + user.getImageUrl()).apply(Arad.opts_circle).into(iv_head);
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (rl_address_manager == v) {
            startActivity(AddressListActivity.class);
        }

//        if (tv_log_out == v) {
//
//        }

        if (ll_header == v) {
            if (CommonUtils.isLoginToActivity(this)) {
                PermissionUtil.handleMultiPermission(this, "读写手机存储", new PermissionUtil.PermissionListener() {
                    @Override
                    public void onPermissionOk(boolean isOk) {
                        if (isOk) {
                            //startActivity(UserMessageActivity.class);
                            Intent intent = new Intent(AccountSettingActivity.this, ImageGridActivity.class);
                            setMaxPage(1);
                            startActivityForResult(intent, 979);
                        }
                    }

                    @Override
                    public void onOpenPermissionPage(boolean isOpen) {
                    }
                }, Permission.Group.STORAGE);
            }
        }

        if (rl_account_and_security == v) {
            startActivity(AccountSecurityActivity.class);
        }

        if (rl_nickname == v) {
            showDialogNick();
        }

        if (rl_sex == v) {
            showDialogSex();
        }
    }

    private void showDialogNick() {
        View view = View.inflate(this, R.layout.item_nick_dialog, null);
        alertDialog.setView(view);
        TextView tv_confirm = view.findViewById(R.id.tv_confirm);
        TextView tv_cancle = view.findViewById(R.id.tv_cancle);
        final EditText et_user_name = view.findViewById(R.id.et_user_name);
        tv_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                userNick = et_user_name.getText().toString();
                showProgress();
                mPresenter.updateUserInfo(AppHolder.instance().getUser().getId(), userNick, null);
            }
        });

        tv_cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
            }
        });

        alertDialog.show();
    }

    private void showDialogSex() {
        View view = View.inflate(this, R.layout.item_dialog_sex, null);
        popupWindow = new PopupWindow(view, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT, true);
        TextView tv_man = view.findViewById(R.id.tv_man);
        TextView tv_woman = view.findViewById(R.id.tv_woman);
        TextView tv_cancle = view.findViewById(R.id.tv_cancel);
        tv_man.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sexStatus = "1";
                sex = "男";
                showProgress();
                mPresenter.updateUserInfo(AppHolder.instance().getUser().getId(), null, sexStatus);
            }
        });

        tv_woman.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sexStatus = "0";
                sex = "女";
                showProgress();
                mPresenter.updateUserInfo(AppHolder.instance().getUser().getId(), null, sexStatus);
            }
        });

        tv_cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
//        popupWindow.
        //设置背景半透明色
        backgroundAlpha(0.5f);
        //popupWindow  事件监听
        popupWindow.setOnDismissListener(new PopupDismissListener());
        View rootView = LayoutInflater.from(AccountSettingActivity.this).inflate(R.layout.activity_account_setting, null);
        popupWindow.showAtLocation(rootView, Gravity.BOTTOM, 0, 0);
    }


    private void setListener() {
        rl_address_manager.setOnClickListener(this);
        rl_nickname.setOnClickListener(this);
        rl_sex.setOnClickListener(this);
        rl_account_and_security.setOnClickListener(this);
        rl_setting.setOnClickListener(this);
//        tv_log_out.setOnClickListener(this);
        ll_header.setOnClickListener(this);
    }

    @Override
    protected void initViews() {
        super.initViews();
        setHeadTitle("账号信息");
        rl_address_manager = findViewById(R.id.rl_address_manager);
        rl_nickname = findViewById(R.id.rl_nickname);
        rl_sex = findViewById(R.id.rl_sex);
        rl_account_and_security = findViewById(R.id.rl_account_and_security);
        rl_setting = findViewById(R.id.rl_setting);
        ll_header = findViewById(R.id.ll_header);

        tv_nickname = findViewById(R.id.tv_nickname);
        tv_sex = findViewById(R.id.tv_sex);
        iv_head = findViewById(R.id.iv_head);

        alertDialog = new AlertDialog.Builder(this).create();
        setListener();
    }

    @Override
    protected void onResume() {
        super.onResume();
        initData();
    }

    private void setMaxPage(int i) {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new GlideImageLoader());   //设置图片加载器
        imagePicker.setShowCamera(true);  //显示拍照按钮
        imagePicker.setCrop(false);
        imagePicker.setSelectLimit(i);
        imagePicker.setSaveRectangle(true); //是否按矩形区域保存
        imagePicker.setStyle(CropImageView.Style.RECTANGLE);  //裁剪框的形状
        imagePicker.setFocusWidth(800);   //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight(800);  //裁剪框的高度。单位像素（圆形自动取宽高最小值）
        imagePicker.setOutPutX(1000);//保存文件的宽度。单位像素
        imagePicker.setOutPutY(1000);//保存文件的高度。单位像素
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 979) {
            if (data != null) {
                imageItems = data.getParcelableArrayListExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                File file = new File(imageItems.get(0).path);
                showProgress();
                MultipartBody multipartBody = mPresenter.updateUserHead(AppHolder.instance().getUser().getId(), file);
                mPresenter.updateUserHead(multipartBody);
            }
        }

    }

    @Override
    public void setHeadImage() {
        Glide.with(AccountSettingActivity.this).load(imageItems.get(0).path).apply(Arad.opts_circle).into(iv_head);
    }

    @Override
    public void setUserSuc() {
        if (!TextUtils.isEmpty(userNick)) {
            tv_nickname.setText(userNick);
        }
        if (!TextUtils.isEmpty(sexStatus) && !TextUtils.isEmpty(sex)) {
            tv_sex.setText(sex);
        }
        alertDialog.dismiss();
        if (popupWindow != null) {
            popupWindow.dismiss();
        }
    }

    class PopupDismissListener implements PopupWindow.OnDismissListener {

        @Override
        public void onDismiss() {
            backgroundAlpha(1f);
        }
    }

    private void backgroundAlpha(float v) {
        WindowManager.LayoutParams layoutParams = getWindow().getAttributes();
        layoutParams.alpha = v;
        getWindow().setAttributes(layoutParams);
    }
}
